use crate::models::Tags;
use fluffy::{db, model::Model};

lazy_static! {
    pub static ref TAGS: Vec<Tags> =  { 
        let mut conn = db::get_conn();
        let mut tags = vec![];
        
        let query = query![
            fields => "id, name",
            order_by => "seq DESC",
            limit => 100,
        ];
        let rows = Tags::fetch_rows(&mut conn, &query, None);
        for r in rows { 
            let (id, name): (usize, String) = from_row!(r);
            tags.push(Tags { id, name});
        }

        tags
    };
}

pub fn get_tag_links(tag_ids: String) -> String { 
    let cache_tags = &*TAGS;
    let mut tag_links = vec![];
    let ids = tag_ids.split(",").collect::<Vec<&str>>();
    for id in &ids { 
        for tag in cache_tags { 
            let id_str = tag.id.to_string();
            if &id_str == id { 
                let tag_link = format!("<a href='{}'>{}</a>", id_str, tag.name);
                tag_links.push(tag_link);
                break;
            }
        }
    }
    tag_links.join(" ")
}
